from app.extensions import get_db
from app.models.Clas import Clas
from app.schames.Clas import ClasSchema, ClasCreate
from app.services.ClasService import ClasService
from fastapi import APIRouter
from fastapi.responses import JSONResponse

clas_router = APIRouter(prefix="/clas", tags=["班级管理"])

@clas_router.get("/", summary="搜索班级")
def get_by_keyword(keyword: str = ""):
    with get_db() as db: # 链接数据库
        # 创建service对象并调用服务
        svc = ClasService(db)
        response = svc.get_by_keyword(keyword)
        return JSONResponse(
            content={
                "data": [ClasSchema.model_validate(item).model_dump() for item in response["data"]],   # ORM转为dict
                "message": response["message"]
            },
            status_code=response["code"]
        )
@clas_router.post("/", summary="增加班级")
def add_clas(clas: ClasCreate):
    with get_db() as db:  # 链接数据库
        svc = ClasService(db)
        response = svc.add_clas(clas.name)
        return JSONResponse(
            content={
                "data": response["data"],   # ORM转为dict
                "message": response["message"]
            },
            status_code=response["code"]
        )

@clas_router.put("/{clas_id}", summary="修改班级")
def update_clas(clas_id: int, clas: ClasCreate):
    with get_db() as db:  # 链接数据库
        svc = ClasService(db)
        response = svc.update_clas(clas_id, clas.name)
        return JSONResponse(
            content={
                "data": response["data"],   # ORM转为dict
                "message": response["message"]
            },
            status_code=response["code"]
        )

@clas_router.delete("/{clas_id}", summary="删除班级")
def delete_clas(clas_id: int):
    with get_db() as db:  # 链接数据库
        svc = ClasService(db)
        response = svc.delete_clas(clas_id)
        return JSONResponse(
            content={
                "data": response["data"],   # ORM转为dict
                "message": response["message"]
            },
            status_code=response["code"]
        )

